package interaction.audio;

import interaction.sampling.Sample;
import processing.core.PApplet;
import ddf.minim.AudioInput;
import ddf.minim.Minim;
import ddf.minim.analysis.BeatDetect;
import ddf.minim.analysis.FFT;

public class AudioProcessor {
	private Minim minim;
	private AudioInput in;
	private BeatDetect beat;
	private FFT fft;
	
	public AudioProcessor(PApplet a)
	{
		minim = new Minim(a);
		minim.debugOn();
	}
	
	public AudioInput getLineIn()
	{
		if (null == in) {
			in = minim.getLineIn(Minim.STEREO, 256);
		}
		return in;
	}
	
	public BeatDetect getBeatDetector()
	{
		if (null == beat) {
			beat = new BeatDetect();
			beat.setSensitivity(50);
			beat.detectMode(BeatDetect.SOUND_ENERGY);
		}
		return beat;
	}
	
	public FFT getFFT()
	{
		if (null == fft) {
			fft = new FFT(in.bufferSize(), in.sampleRate());
			fft.linAverages(64);
		}
		return fft;
	}
	
	public Sample getAudioSpectrumSample()
	{
		return Sample.fromFftAverages(getFFT());
	}

	public boolean beatDetected() {
		return getBeatDetector().isOnset();
//		int matches = 0;
//		for (int i = 0; i < 26; i++) {
//			if (getBeatDetector().isRange(i, i+1, 1)) {
//				matches++;
//			}
//		}
//		return matches > 10;
	}
	
	public void process()
	{
		getBeatDetector().detect(getLineIn().mix);
		getFFT().forward(getLineIn().mix);
	}
	
	protected void finalize() throws Throwable {
		if (null != in) {
			in.close();
		}
		minim.stop();
		super.finalize();
	}
}
